import BasePlugin from './BasePlugin';

/**
 * 变换插件 - 处理对象变换
 */
export default class TransformPlugin extends BasePlugin {
    constructor() {
        super();
        this.transformations = new Map();
        this.snapAngle = 15;
        this.snapThreshold = 5;
        this.isSnapping = true;
    }

    /**
     * 初始化插件
     */
    init(editor) {
        super.init(editor);
        this._setupEventListeners();
    }

    /**
     * 启用对象变换功能
     */
    enable() {
        super.enable();
        this.isSnapping = true;
    }

    /**
     * 禁用对象变换功能
     */
    disable() {
        super.disable();
        this.isSnapping = false;
    }

    /**
     * 设置旋转角度吸附值
     */
    setSnapAngle(angle) {
        this.snapAngle = angle;
    }

    /**
     * 设置吸附阈值
     */
    setSnapThreshold(threshold) {
        this.snapThreshold = threshold;
    }

    /**
     * 旋转对象
     */
    rotate(angle) {
        if (!this.isEnabled() || !this.canvas) return;

        const objects = this._getSelectedObjects();
        objects.forEach(obj => {
            obj.rotate(obj.angle + angle);
        });

        this.canvas.renderAll();
        this._emitTransformEvent('rotate', { angle });
    }

    /**
     * 翻转对象
     */
    flip(direction) {
        if (!this.isEnabled() || !this.canvas) return;

        const objects = this._getSelectedObjects();
        objects.forEach(obj => {
            if (direction === 'horizontal') {
                obj.flipX = !obj.flipX;
            } else if (direction === 'vertical') {
                obj.flipY = !obj.flipY;
            }
        });

        this.canvas.renderAll();
        this._emitTransformEvent('flip', { direction });
    }

    /**
     * 缩放对象
     */
    scale(scaleX, scaleY) {
        if (!this.isEnabled() || !this.canvas) return;

        const objects = this._getSelectedObjects();
        objects.forEach(obj => {
            obj.scale(scaleX, scaleY);
        });

        this.canvas.renderAll();
        this._emitTransformEvent('scale', { scaleX, scaleY });
    }

    /**
     * 设置对象大小
     */
    setSize(width, height, maintainAspectRatio = false) {
        if (!this.isEnabled() || !this.canvas) return;

        const objects = this._getSelectedObjects();
        objects.forEach(obj => {
            const currentWidth = obj.getScaledWidth();
            const currentHeight = obj.getScaledHeight();

            if (maintainAspectRatio) {
                const ratio = currentWidth / currentHeight;
                if (width) {
                    height = width / ratio;
                } else if (height) {
                    width = height * ratio;
                }
            }

            const scaleX = width ? width / obj.width : obj.scaleX;
            const scaleY = height ? height / obj.height : obj.scaleY;

            obj.scale(scaleX, scaleY);
        });

        this.canvas.renderAll();
        this._emitTransformEvent('resize', { width, height });
    }

    /**
     * 设置对象位置
     */
    setPosition(left, top) {
        if (!this.isEnabled() || !this.canvas) return;

        const objects = this._getSelectedObjects();
        objects.forEach(obj => {
            if (typeof left === 'number') obj.set('left', left);
            if (typeof top === 'number') obj.set('top', top);
        });

        this.canvas.renderAll();
        this._emitTransformEvent('move', { left, top });
    }

    /**
     * 设置对象角度
     */
    setAngle(angle) {
        if (!this.isEnabled() || !this.canvas) return;

        const objects = this._getSelectedObjects();
        objects.forEach(obj => {
            obj.rotate(angle);
        });

        this.canvas.renderAll();
        this._emitTransformEvent('rotate', { angle });
    }

    /**
     * 设置对象原点
     */
    setOrigin(originX, originY) {
        if (!this.isEnabled() || !this.canvas) return;

        const objects = this._getSelectedObjects();
        objects.forEach(obj => {
            if (originX) obj.set('originX', originX);
            if (originY) obj.set('originY', originY);
        });

        this.canvas.renderAll();
        this._emitTransformEvent('setOrigin', { originX, originY });
    }

    /**
     * 获取选中对象
     */
    _getSelectedObjects() {
        const activeObject = this.canvas.getActiveObject();
        return activeObject && activeObject.type === 'activeSelection'
            ? activeObject.getObjects()
            : [activeObject];
    }

    /**
     * 发送变换事件
     */
    _emitTransformEvent(type, data) {
        this.editor.emit('transform:applied', {
            type,
            data,
            objects: this._getSelectedObjects()
        });
    }

    /**
     * 设置事件监听
     */
    _setupEventListeners() {
        if (!this.canvas) return;

        // 监听对象旋转事件
        this.canvas.on('object:rotating', (e) => {
            if (!this.isEnabled() || !this.isSnapping) return;

            const target = e.target;
            const angle = target.angle;

            // 角度吸附
            const snappedAngle = Math.round(angle / this.snapAngle) * this.snapAngle;
            if (Math.abs(angle - snappedAngle) < this.snapThreshold) {
                target.rotate(snappedAngle);
            }
        });

        // 监听对象缩放事件
        this.canvas.on('object:scaling', (e) => {
            if (!this.isEnabled()) return;

            const target = e.target;
            const transform = this.transformations.get(target);

            // 记录变换状态
            if (!transform) {
                this.transformations.set(target, {
                    original: {
                        width: target.width,
                        height: target.height,
                        scaleX: target.scaleX,
                        scaleY: target.scaleY
                    }
                });
            }
        });

        // 监听对象移动事件
        this.canvas.on('object:moving', (e) => {
            if (!this.isEnabled() || !this.isSnapping) return;

            const target = e.target;
            const gridSize = 10; // 网格大小

            // 网格吸附
            if (Math.abs(target.left % gridSize) < this.snapThreshold) {
                target.set('left', Math.round(target.left / gridSize) * gridSize);
            }
            if (Math.abs(target.top % gridSize) < this.snapThreshold) {
                target.set('top', Math.round(target.top / gridSize) * gridSize);
            }
        });

        // 监听对象修改完成事件
        this.canvas.on('object:modified', (e) => {
            const target = e.target;
            this.transformations.delete(target);
        });
    }

    /**
     * 销毁插件
     */
    destroy() {
        if (this.canvas) {
            this.transformations.clear();
        }
        super.destroy();
    }
} 